import { FC, useEffect, useRef, useState } from 'react'
import Taro, { useDidShow, useShareAppMessage } from '@tarojs/taro'
import { AtTabs, AtTabsPane } from 'taro-ui'
import pic2 from '../../resource/pic2.png'
import arrow from '../../resource/arrow.png'
import style from './style.less'
import { Button } from '@tarojs/components'

const Order: FC = () => {
  const [current, setCurrent] = useState(0)
  const tabList = useRef([{ title: '运输中' }, { title: '已完成' }, { title: '已取消' }])

  const [list, setList] = useState<any[]>([])
  const [completeList, setCompleteList] = useState<any[]>([])
  const [cancelList, setCancelList] = useState<any[]>([])

  useEffect(() => {
    if (!Taro.getStorageSync('auth')) {
      return
    }
    if (current === 0) {
      getInTransitReq()
    } else if (current === 1) {
      getCompleteReq()
    } else if (current === 2) {
      getCancelReq()
    }
  }, [current])

  useDidShow(() => {
    if (!Taro.getStorageSync('auth')) {
      return
    }
    if (current === 0) {
      getInTransitReq()
    } else if (current === 1) {
      getCompleteReq()
    } else if (current === 2) {
      getCancelReq()
    }
  })

  useShareAppMessage(res => {
    if (res.from === 'button') {
      // 来自页面内转发按钮
      console.log(res.target)
    }
    return {
      title: '我正在使用满满运抢单，快来试试吧'
    }
  })

  const getInTransitReq = () => {
    Taro.showLoading({ title: '加载中' })
    Taro.request({
      url: 'http://139.9.123.88:8083/fta-trade/order/driver/getOrderList',
      method: 'POST',
      data: JSON.stringify({
        openId: Taro.getStorageSync('token')
        // openId: 'o4ZIg47fUX_fpbvoq6uCsTIyBldQ'
      }),
      success: (data) => {
        console.log('运输中订单', data.data);
        setList(data.data.data.orders)
        Taro.hideLoading()
      },
      fail: () => {
        Taro.hideLoading()
        console.log('请求订单失败');
      }
    })
  }

  const getCompleteReq = () => {
    Taro.showLoading({ title: '加载中' })
    Taro.request({
      url: 'http://139.9.123.88:8083/fta-trade/order/driver/getCompletedOrders',
      method: 'POST',
      data: JSON.stringify({
        openId: Taro.getStorageSync('token')
        // openId: 'o4ZIg47fUX_fpbvoq6uCsTIyBldQ'
      }),
      success: (data) => {
        console.log('已完成订单', data.data);
        setCompleteList(data.data.data.orders)
        Taro.hideLoading()
      },
      fail: () => {
        Taro.hideLoading()
        console.log('请求订单失败');
      }
    })
  }

  const getCancelReq = () => {
    Taro.showLoading({ title: '加载中' })
    Taro.request({
      url: 'http://139.9.123.88:8083/fta-trade/order/driver/getCanceledOrders',
      method: 'POST',
      data: JSON.stringify({
        openId: Taro.getStorageSync('token')
        // openId: 'o4ZIg47fUX_fpbvoq6uCsTIyBldQ'
      }),
      success: (data) => {
        console.log('已取消订单', data.data);
        setCancelList(data.data.data.orders)
        Taro.hideLoading()
      },
      fail: () => {
        Taro.hideLoading()
        console.log('请求订单失败');
      }
    })
  }

  const handleClick = (value) => {
    setCurrent(value)
  }

  const cancel = (num, isBackDeposit, orderNumber) => {
    if (num === 1) {
      Taro.showModal({
        title: '提示',
        content: '取消订单后，订金将全额返还给您',
        success: function (res) {
          if (res.confirm) {
            Taro.request({
              url: 'http://139.9.123.88:8083/fta-trade/order/driver/cancelOrder',
              method: 'POST',
              data: JSON.stringify({
                orderNumber: orderNumber,
                openId: Taro.getStorageSync('token'),
              }),
              success: () => {
                setCurrent(2)
              },
              fail: () => {
                console.log('取消订单失败');
              }
            })
          } else if (res.cancel) {
            console.log('用户点击取消')
          }
        }
      })
    } else if (num === 2) {
      Taro.showModal({
        title: '提示',
        content: isBackDeposit ? '该单订金将扣除50%赔付给货主，是否确认取消' : '该单订金将全额赔付给货主，是否确认取消',
        success: function (res) {
          if (res.confirm) {
            Taro.request({
              url: 'http://139.9.123.88:8083/fta-trade/order/driver/cancelOrder',
              method: 'POST',
              data: JSON.stringify({
                orderNumber: orderNumber,
                openId: Taro.getStorageSync('token'),
              }),
              success: () => {
                setCurrent(2)
              },
              fail: () => {
                console.log('取消订单失败');
              }
            })
          } else if (res.cancel) {
            console.log('用户点击取消')
          }
        }
      })
    }
  }

  const handleLoading = (num, orderNumber) => {
    if (num !== 2) {
      return
    }
    Taro.showModal({
      title: '提示',
      content: '确认装货后，则不能再取消该订单',
      success: function (res) {
        if (res.confirm) {
          Taro.request({
            url: 'http://139.9.123.88:8083/fta-trade/order/driver/loadOrder',
            method: 'POST',
            data: JSON.stringify({
              orderNumber: orderNumber,
              openId: Taro.getStorageSync('token'),
            }),
            success: () => {
              console.log('装货成功后调用');
              getInTransitReq()
            },
            fail: () => {
              console.log('装货失败');
            }
          })
        } else if (res.cancel) {
          console.log('用户点击取消')
        }
      }
    })
  }

  const handleUnloading = (num, orderNumber, addr, addr2) => {
    if (num !== 5) {
      return
    }
    Taro.navigateTo({ url: `/packageB/receipt/index?orderNumber=${orderNumber}&addr=${addr}&addr2=${addr2}` })
  }

  const getInTransit = () => {
    if (list.length === 0) {
      return (
        <div className="unLogin">
          <img src={pic2} />
          <div>暂无订单～</div>
        </div>
      )
    }
    return (
      <div className="body">
        {
          list.map(item => {
            return (
              <div className="box">
                <div className="areaContainer">
                  <div className="areaItem">{item.loadAddress.substring(item.loadAddress.indexOf('-') + 1, item.loadAddress.indexOf(' '))}</div>
                  <img className="areaItem" src={arrow} alt="" />
                  <div className="areaItem">{item.unloadingAdress.substring(item.unloadingAdress.indexOf('-') + 1, item.unloadingAdress.indexOf(' '))}</div>
                </div>
                <div className="detail" onClick={() => { Taro.navigateTo({ url: `/packageB/orderDetail/index?param=${JSON.stringify(item)}&status=1` }) }}>运单详情 <i>{'>'}</i></div>
                <div>{item.cargoName} ｜ {item.truckLength}米 {item.truckType} ｜ {item.truckWeight}吨 ｜ {item.cargoCapacipy}方</div>
                <div className="amountContainer">
                  {item.status === 1 && <div style={{ color: 'red' }}>待货主签订运输协议</div>}
                  {item.status === 2 && <div style={{ color: '#14CD0E' }}>货主已确认协议</div>}
                  {item.status === 5 && <div style={{ color: '#14CD0E' }}>货主已确认协议</div>}
                  {item.status === 6 && <div style={{ color: 'red' }}>待货主支付运费</div>}
                  <div>订金：¥{item.driverPayDeposit}</div>
                  <div>运费：¥{item.totalFreightAmount}</div>
                </div>
                {item.isBackDeposit ? <div className="tips">订金将在货主<i>"确认收货"</i>后立即退还给您</div> :
                  <div className="tips">此订金不退还</div>}
                <div className="btnContainer">
                  <div className={item.status === 5 || item.status === 6 ? 'disable' : ''} onClick={() => { cancel(item.status, item.isBackDeposit, item.orderNumber) }}>取消订单</div>
                  <div className={item.status === 2 ? '' : 'disable'} onClick={() => { handleLoading(item.status, item.orderNumber) }}>我已装货</div>
                  <div className={item.status === 5 ? '' : 'disable'} onClick={() => {
                    handleUnloading(item.status, item.orderNumber,
                      item.loadAddress.substring(item.loadAddress.indexOf('-') + 1, item.loadAddress.indexOf(' '))
                      , item.unloadingAdress.substring(item.unloadingAdress.indexOf('-') + 1, item.unloadingAdress.indexOf(' ')))
                  }}>我已卸货</div>
                </div>
              </div>
            )
          })
        }
      </div>
    )
  }

  const getComplete = () => {
    if (completeList.length === 0) {
      return (
        <div className="unLogin">
          <img src={pic2} />
          <div>暂无订单～</div>
        </div>
      )
    }
    return (
      <div className="body">
        {
          completeList.map(item => {
            return (
              <div className="box" style={{ height: Taro.pxTransform(310) }}>
                <div className="areaContainer">
                  <div className="areaItem">{item.loadAddress.substring(item.loadAddress.indexOf('-') + 1, item.loadAddress.indexOf(' '))}</div>
                  <img className="areaItem" src={arrow} alt="" />
                  <div className="areaItem">{item.unloadingAdress.substring(item.unloadingAdress.indexOf('-') + 1, item.unloadingAdress.indexOf(' '))}</div>
                </div>
                <div className="detail" onClick={() => { Taro.navigateTo({ url: `/packageB/orderDetail/index?param=${JSON.stringify(item)}&status=2` }) }}>运单详情 <i>{'>'}</i></div>
                <div>{item.cargoName} ｜ {item.truckLength}米 {item.truckType} ｜ {item.truckWeight}吨 ｜ {item.cargoCapacipy}方</div>
                <div className="amount">运费：¥{item.totalFreightAmount}</div>
                <div className="btnContainer2">
                  <Button onClick={() => { Taro.navigateTo({ url: '/packageC/evaluate/index' }) }}>去评价</Button>
                  <Button openType="share">分享订单</Button>
                </div>
              </div>
            )
          })
        }
      </div>
    )
  }

  const getCancel = () => {
    if (cancelList.length === 0) {
      return (
        <div className="unLogin">
          <img src={pic2} />
          <div>暂无订单～</div>
        </div>
      )
    }
    return (
      <div className="body">
        {
          cancelList.map(item => {
            return (
              <div className="box" style={{ height: Taro.pxTransform(240) }}>
                <div className="areaContainer">
                  <div className="areaItem">{item.loadAddress.substring(item.loadAddress.indexOf('-') + 1, item.loadAddress.indexOf(' '))}</div>
                  <img className="areaItem" src={arrow} alt="" />
                  <div className="areaItem">{item.unloadingAdress.substring(item.unloadingAdress.indexOf('-') + 1, item.unloadingAdress.indexOf(' '))}</div>
                </div>
                <div className="detail" onClick={() => { Taro.navigateTo({ url: `/packageB/orderDetail/index?param=${JSON.stringify(item)}&status=3` }) }}>运单详情 <i>{'>'}</i></div>
                <div>{item.cargoName} ｜ {item.truckLength}米 {item.truckType} ｜ {item.truckWeight}吨 ｜ {item.cargoCapacipy}方</div>
                <div className="cancelContainer">
                  <div>{item.msg}</div>
                  <div>运费：¥{item.totalFreightAmount}</div>
                </div>
              </div>
            )
          })
        }
      </div>
    )
  }

  return (
    <div className={style.root}>
      <AtTabs current={current} tabList={tabList.current} onClick={handleClick}>
        <div style={{ height: Taro.pxTransform(20) }} />
        <AtTabsPane current={current} index={0} >
          {Taro.getStorageSync('auth') ? getInTransit() :
            <div className="unLogin">
              <img src={pic2} />
              <div>暂无订单～</div>
            </div>}
        </AtTabsPane>
        <AtTabsPane current={current} index={1}>
          {Taro.getStorageSync('auth') ? getComplete() :
            <div className="unLogin">
              <img src={pic2} />
              <div>暂无订单～</div>
            </div>
          }
        </AtTabsPane>
        <AtTabsPane current={current} index={2}>
          {Taro.getStorageSync('auth') ? getCancel() :
            <div className="unLogin">
              <img src={pic2} />
              <div>暂无订单～</div>
            </div>
          }
        </AtTabsPane>
      </AtTabs>

    </div>
  )
}

export default Order